<?php

namespace app\common\model;

use think\Db;

class ShopCartModel extends BaseModel
{
    protected $name = 'shop_cart'; //定义用户表
    //开启自动写入时间戳
    protected $autoWriteTimestamp = false;
    // 定义自动完成的属性
    protected $auto = []; //新增修改
    protected $insert = []; //插入
    protected $update = []; //修改

    /**
     * 增加购物车
     * @param $memberUid
     * @param $skuId
     * @param $num
     * @return bool
     */
    function addCart($memberUid, $skuId, $num)
    {
        $goodsModel = new ShopGoodsModel();
        $skuInfo    = ShopGoodsSkuModel::get($skuId);
        $goodsInfo  = ShopGoodsModel::get($skuInfo['goods_id']);
        if ($goodsInfo['promotion_type'] > 3) {
            $this->error = '集采、竞拍商品不支持加入购物车！';
            return false;
        }
        //检测登陆
        if ($memberUid <= 0) {
            $this->error = '请先登录';
            return false;
        }
        //删除购物车商品
        if ($num <= 0) {
            $this->where('member_uid', $memberUid)->where('sku_id', $skuId)->delete();
            return true;
        }
        $goodsPoint = 0;
        //检测活动状态
        if ($goodsInfo['promotion_type'] > 0) {
            $promotion_status = $goodsModel->checkPromotionGoods($skuInfo['goods_id'], $goodsInfo['promotion_type']);
            if ($promotion_status == 0) {
                $this->error = '该商品活动还未开始!';
                return false;
            }
            if ($promotion_status == -1) {
                $this->error = '该商品活动已结束!';
                return false;
            }
            if ($goodsInfo['promotion_type'] == 3) { //积分商品
                $memberModel = new UserMemberModel();
                $userPoint   = $memberModel->where('uid', $memberUid)->value('pay_points');
                $pointModel  = new ShopPromotionPointModel();
                $goodsPoint  = $pointModel->where('goods_id', $goodsInfo['goods_id'])->value('points');
                $goodsPoint  = $goodsPoint * $num;
                if ($userPoint < $goodsPoint) {
                    $this->error = '您的可用积分不足！';
                    return false;
                }
            }
        }
        //检测最小起订量
        if ($skuInfo['minimum'] > $num) {
            $this->error = '该商品最小起订量为' . $skuInfo['minimum'];
            return false;
        }
        //检测库存
        if ($skuInfo['goods_stock'] < $num) {
            $this->error = '商品库存不足';
            return false;
        }
        //检测购物车数量
        $cartCount = $this->where('member_uid', $memberUid)->count();
        if ($cartCount > 50) {
            $this->error = '对不起，购物车最多存放50件商品';
            return false;
        }
        //阶梯价计算
        $resultPrice = $goodsModel->calcPrice($skuInfo['goods_price'], $num);
        if ($resultPrice == false) {
            $this->error = $goodsModel->getError();
            return false;
        }
        //检测购物车是否存在该数据
        $cartInfo = $this->where('member_uid', $memberUid)->where('sku_id', $skuId)->find();
        //加入购物车
        if ($cartInfo) { //更新
            if ($goodsInfo['give_integral'] == -1) {
                $givePoint = ceil($resultPrice * $num);
            } else {
                $givePoint = $goodsInfo['give_integral'];
            }
            $saveData = ['num' => $num, 'price' => $resultPrice, 'give_point' => $givePoint, 'goods_point' => $goodsPoint];
            $this->where('cart_id', $cartInfo['cart_id'])->update($saveData);
        } else { //新增
            if ($goodsInfo['give_integral'] == -1) {
                $givePoint = ceil($resultPrice * $num);
            } else {
                $givePoint = $goodsInfo['give_integral'];
            }
            $cartData = [
                'member_uid'       => $memberUid,
                'site_id'          => $goodsInfo['site_id'],
                'sku_sn'           => $skuInfo['sku_sn'],
                'goods_id'         => $goodsInfo['goods_id'],
                'goods_name'       => $goodsInfo['goods_name'],
                'sku_name'         => $skuInfo['sku_name'],
                'step'             => $skuInfo['step'],
                'goods_unit'       => $goodsInfo['goods_unit'],
                'sku_id'           => $skuId,
                'goods_thumb'      => $goodsInfo->getAttr('goods_thumb'),
                'price'            => $resultPrice,
                'goods_point'      => $goodsPoint,
                'give_point'       => $givePoint,
                'num'              => $num,
                'promotion_type'   => $goodsInfo['promotion_type'],
                'promotion_status' => $goodsInfo['promotion_status'],
                'cart_status'      => 1,
                'createtime'       => time(),
                'goods_price'      => $skuInfo['goods_price'],
                'goods_weight'     => $skuInfo['goods_weight'],
            ];
            $this->addData($cartData);
        }
        return true;
    }

    /**
     * 计算购物车总数量，金额
     * @param $memberUid
     * @param int|array $cartStatus 如果传入数字代表状态，如果非数字表示skuIds
     * @param int $siteId
     * @return mixed
     */
    public function cartTotal($siteId, $memberUid, $cartStatus = 2)
    {
        $map['site_id']    = $siteId;
        $map['member_uid'] = $memberUid;
        if ($cartStatus == 0) { //失效商品
            $map['cart_status'] = 0;
        }
        if ($cartStatus == 1) { //正常商品
            $map['cart_status'] = 1;
        }
        if (!is_numeric($cartStatus)) {
            $map['sku_id'] = ['in', $cartStatus];
        }
        $total = $this->field('sum(num) as sum_num,sum(price*num) as total_price,sum(goods_point) as total_goods_point,sum(give_point) as total_give_point')->where($map)->find()->toArray();
        if (is_null($total['sum_num'])) {
            $total['sum_num'] = 0;
        }
        if (is_null($total['total_price'])) {
            $total['total_price'] = 0;
        }
        if (is_null($total['total_goods_point'])) {
            $total['total_goods_point'] = 0;
        }
        if (is_null($total['total_give_point'])) {
            $total['total_give_point'] = 0;
        }
        return $total;
    }

    /**
     * 购物车列表，按siteID区分
     * @param int $siteId
     * @param $memberUid
     * @param int $cartStatus $cartStatus 如果传入数字代表状态，如果传入非数字代表skuIds,promotionType失效
     * @return mixed
     */
    public function cartList($siteId, $memberUid, $cartStatus = 2)
    {
        $map['site_id']    = $siteId;
        $map['member_uid'] = $memberUid;
        if ($cartStatus == 0) { //失效商品
            $map['cart_status'] = 0;
        }
        if ($cartStatus == 1) { //正常商品
            $map['cart_status'] = 1;
        }
        if (!is_numeric($cartStatus)) {
            $map['sku_id'] = ['in', $cartStatus];
        }
        $cartList = $this->where($map)->select();
        if ($cartList->isEmpty()) {
            return [];
        } else {
            $cartList     = $cartList->toArray();
            $totalNum     = $totalPrice = $totalGivePoint = $totalGoodsPoint = 0;
            $siteCartList = [];
            $skuIds       = array_column($cartList, 'sku_id');
            $skuModel     = new ShopGoodsSkuModel();
            $skuList      = $skuModel->where('sku_id', 'in', $skuIds)->column('minimum,goods_stock', 'sku_id');
            foreach ($cartList as $k => $v) {
                $v                           = format_goods_content($v);
                $v['price']                  = floatval($v['price']); //商品单价
                $v['goods_total']            = $v['num'] * $v['price']; //商品合计价格
                $v['minimum']                = $skuList[$v['sku_id']]['minimum']; //最小起订量
                $v['goods_stock']            = $skuList[$v['sku_id']]['goods_stock']; //商品库存
                $siteCartList['item_list'][] = $v;
                $totalNum                    += $v['num']; //总数量
                $totalPrice                  += round($v['num'] * $v['price'], 4);
                $totalGivePoint              += $v['give_point'];
                $totalGoodsPoint             += $v['goods_point'];
            }
            $siteCartList['num']               = count($siteCartList['item_list']); //店铺名称
            $siteCartList['site_name']         = get_site_name($siteId); //店铺名称
            $siteCartList['sku_ids']           = implode(',', $skuIds); //sku_id串
            $siteCartList['total_num']         = $totalNum; //总数量
            $siteCartList['total_price']       = $totalPrice; //总价格
            $siteCartList['total_give_point']  = $totalGivePoint; //总赠送积分
            $siteCartList['total_goods_point'] = $totalGoodsPoint; //总消费积分
            return $siteCartList;
        }
    }

    /**
     * 删除购物车
     * @param $ids 主键
     * @param $uid 用户ID
     * @return mixed
     */
    public function delCart($ids)
    {
        $map['cart_id'] = ['in', $ids];
        $this->where($map)->delete();
        return true;
    }

    /**
     * 清空购物车
     * @param $memberUid 会员ID
     * @param int $cartStatus 商品状态 0失效 1正常 2全部商品
     * @param int $siteId
     * @return bool
     */
    public function clearCart($siteId, $memberUid, $cartStatus = 2)
    {
        $map['site_id']    = $siteId;
        $map['member_uid'] = $memberUid;
        if ($cartStatus == 0) { //清空失效商品
            $map['cart_status'] = 0;
        }
        if ($cartStatus == 1) { //清空正常商品
            $map['cart_status'] = 1;
        }
        $this->where($map)->delete();
        return true;
    }

    /**
     * 刷新购物车 库存和活动状态
     * @param integer $memberUid 购买用户id
     * @param int $siteId 站点id
     * @return bool 是否通过
     */
    public function refreshCart($siteId, $memberUid)
    {
        $goodsModel         = new ShopGoodsModel();
        $goodsSkuModel      = new ShopGoodsSkuModel();
        $map['member_uid']  = $memberUid;
        $map['cart_status'] = 1; //只刷正常商品
        $map['site_id']     = $siteId;
        //取比对库存
        $cart        = $this->where($map)->column('num,goods_id,promotion_type,promotion_status', 'sku_id');
        $info        = $goodsSkuModel->where('sku_id', 'in', array_keys($cart))->column('goods_stock,goods_id', 'sku_id');
        $stockSkuIds = []; //库存异常商品
        $end         = true;
        foreach ($cart as $k => $v) {
            //记录库存异常数据
            if ($v['num'] > $info[$k]['goods_stock']) {
                $stockSkuIds[] = $k;
            }
            //更新商品活动状态记录
            if ($v['promotion_type'] > 0) {
                $goodsId = $goodsModel->checkPromotionGoods($v['goods_id'], $v['promotion_type']);
                if (is_numeric($goodsId)) { //返回数字表示该goods_id商品已失效
                    $end = false;
                    $this->where('member_uid', $memberUid)->where('goods_id', $goodsId)->setField('cart_status', 0);
                }
            }
        }
        if (!empty($stockSkuIds)) {
            $map['sku_id'] = ['in', $stockSkuIds];
            Db::name('shop_cart')->where($map)->setField('cart_status', 0); //设置失效
            $end = false;
        }
        return $end;
    }

}